const app = getApp();
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");
const util = require("../../../utils/util");

Page({
  data: {
    clazzName: null, // 班级名称
    invitationCode: null, // 邀请码
    teacherTotal: null, // 教师联系方式总数
    teacherList: [],
    studentTotal: null, // 学生联系方式总数
    studentList: [],
    userType: 2,
    params: null,
  },
  onShow() {
    let userType = app.globalData.userType;
    let userList = userType == 1 ? app.globalData.teacherInfo : app.globalData.parentInfo;
    let userInfo = {};
    let selectedClazz = app.globalData.selectedClazz;
    let selectedGrade = app.globalData.selectedGrade;

    // 如果没数据就直接返回不找了
    if (!userList.length > 0) {
      return null;
    }

    for (let i of userList) {
      if (i.clazz == selectedClazz && i.grade == selectedGrade) {
        userInfo = i;
      }
    }
    let params = {
      schoolId: userInfo.schoolId,
      grade: userInfo.grade,
      clazz: userInfo.clazz,
      studyType: userInfo.studyType
    }
    this.getClassTeacherList(params);
    this.getClassStudentList(params);
    this.setData({
      userType,
      params,
    })
  },
  async getClassTeacherList(params) {
    let res = await requestUtil.request('POST', api.getClassTeacherList, params);
    let teacherInfoList = res.data.data;
    let teacherList = [];
    for (let i of teacherInfoList) {
      let obj = {
        id: i.id,
        name: i.teacherName,
        position: i.teacherSubject + '老师'
      }
      teacherList.push(obj);
    }
    this.setData({
      teacherTotal: teacherInfoList.length,
      teacherInfoList,
      teacherList
    })
  },
  async getClassStudentList(params) {
    let res = await requestUtil.request('POST', api.getClassStudentList, params);
    let studentInfoList = res.data.data;
    let studentList = [];
    for (let i of studentInfoList) {
      let obj = {
        id: i.id,
        no: i.studentNum,
        name: i.name,
      };
      studentList.push(obj);
    }
    this.setData({
      clazzName: studentInfoList[0].gradeName + studentInfoList[0].clazz + '班',
      studentTotal: studentInfoList.length,
      studentInfoList,
      studentList
    })
  },

  onShareAppMessage: function (obj) {
    return {
      title: '邀请您加入班级',
      // path: api.navigateUrl.invitePage + '?code=' + this.data.invitationCode + '&type=student',
      path: '/pages/index/index/index',
      imageUrl: '../../../img/main.png'
    }
  },

  onCall: function (e) {
    let phone = e.currentTarget.dataset.phone;
    if (!util.isNullOrEmpty(phone)) {
      wx.makePhoneCall({
        phoneNumber: phone,
        fail: function () {}
      })
    }
  },

  onChat: function (e) {
    let id = e.currentTarget.dataset.id;
    if (!util.isNullOrEmpty(id)) {
      wx.navigateTo({
        url: api.navigateUrl.chatPage + '?id=' + id
      })
    }
  }
});